<script setup lang="ts">
import VDialog from "@/components/VDialog/VDialog.vue";
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import {
  downloadUserScoreRecordTemplateApi,
  importUserScoreRecordApi,
  UserScoreRecordImportResultDTO
} from "@/api/performance/userScoreRecord";

interface Props {
  modelValue: boolean;
}

const props = defineProps<Props>();
const emits = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set(v) {
    emits("update:modelValue", v);
  }
});

const title = computed(() => {
  return "导入用户分数记录";
});

const formData = reactive({
  file: null as File | null
});

const formRef = ref<FormInstance>();
const loading = ref(false);
const uploadRef = ref();
const importResult = ref<UserScoreRecordImportResultDTO | null>(null);
const showResult = ref(false);

// 下载模板
async function handleDownloadTemplate() {
  try {
    await downloadUserScoreRecordTemplateApi();
    ElMessage.success("模板下载成功");
  } catch (error) {
    ElMessage.error("模板下载失败");
    console.error("下载模板失败:", error);
  }
}

// 处理文件选择
function handleFileChange(file: File) {
  formData.file = file;
  importResult.value = null;
  showResult.value = false;
}

// 上传文件
async function handleConfirm() {
  if (!formData.file) {
    ElMessage.warning("请选择要上传的Excel文件");
    return;
  }

  loading.value = true;
  try {
    const response = await importUserScoreRecordApi(formData.file);
    
    if (response.data) {
      importResult.value = response.data;
      showResult.value = true;
      
      if (response.data.failCount === 0) {
        ElMessage.success(
          `导入成功！成功导入 ${response.data.successCount} 条数据`
        );
        visible.value = false;
        emits("success");
      } else {
        ElMessage.warning(
          `导入完成！成功 ${response.data.successCount} 条，失败 ${response.data.failCount} 条，请查看失败详情`
        );
      }
    } else {
      ElMessage.success("导入成功");
      visible.value = false;
      emits("success");
    }
  } catch (e: any) {
    console.error("导入失败:", e);
    const errorMsg =
      e?.response?.data?.msg || e?.message || "导入失败，请检查文件格式是否正确";
    ElMessage.error(errorMsg);
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.modelValue,
  val => {
    if (val) {
      // Reset form when modal opens
      formRef.value?.resetFields();
      formData.file = null;
      importResult.value = null;
      showResult.value = false;
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
    }
  }
);
</script>

<template>
  <v-dialog
    :title="title"
    v-model="visible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="visible = false"
    class="userScoreRecord-import-modal"
    width="600px"
    confirm-text="上传"
    cancel-text="取消"
  >
    <div style="margin-top: 20px; margin-left: 30px; margin-right: 30px;">
      <!-- 导入教程文字 -->
      <div
        style="
          margin-bottom: 20px;
          padding: 10px;
          background-color: #f5f7fa;
          border-radius: 4px;
        "
      >
        <p style="font-size: 14px; line-height: 1.6;">
          <strong>导入教程：</strong><br />
          1. 先点击下方的"下载模板"按钮下载Excel模板文件<br />
          2. 在模板中填写数据（注意不要出现任何格式错误）<br />
          3. 点击"上传文件"按钮选择填好的Excel文件<br />
          4. 点击"上传"按钮完成导入
        </p>
      </div>

      <!-- 表单 -->
      <el-form :model="formData" ref="formRef">
        <el-form-item style="margin-top: 30px; display: flex; justify-content: center; align-items: center; flex-direction: column;">
          <div style="display: flex; gap: 12px; justify-content: center;">
            <el-button type="primary" @click="handleDownloadTemplate">
              下载模板
            </el-button>
            <el-upload
              ref="uploadRef"
              :show-file-list="false"
              :before-upload="(file) => { handleFileChange(file); return false; }"
              accept=".xlsx,.xls"
            >
              <el-button type="primary"> 上传文件 </el-button>
            </el-upload>
          </div>
          <div v-if="formData.file" class="mt-2 text-success" style="text-align: center;">
            已选择文件: {{ formData.file.name }}
          </div>
        </el-form-item>
      </el-form>

      <!-- 导入结果 -->
      <div v-if="showResult && importResult" style="margin-top: 20px;">
        <el-divider />
        <div style="margin-bottom: 10px;">
          <el-alert
            :type="importResult.failCount === 0 ? 'success' : 'warning'"
            :closable="false"
            show-icon
          >
            <template #title>
              <div>
                <p>导入结果：成功 {{ importResult.successCount }} 条，失败 {{ importResult.failCount }} 条</p>
              </div>
            </template>
          </el-alert>
        </div>

        <!-- 失败详情 -->
        <div
          v-if="importResult.failCount > 0 && importResult.failureDetails?.length > 0"
          style="margin-top: 15px;"
        >
          <el-collapse>
            <el-collapse-item title="失败详情" name="failure-details">
              <el-table
                :data="importResult.failureDetails"
                border
                size="small"
                max-height="200"
                style="width: 100%"
              >
                <el-table-column prop="rowNumber" label="行号" width="80" />
                <el-table-column prop="nickname" label="用户姓名" width="120" />
                <el-table-column prop="failureReason" label="失败原因" />
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </v-dialog>
</template>

<style scoped>
.userScoreRecord-import-modal :deep(.el-dialog__body) {
  max-height: 600px;
  overflow-y: auto;
}

.text-success {
  color: #67c23a;
  font-size: 12px;
  margin-top: 8px;
}
</style>

